package com.qf.es.service;

import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import utils.ESClient;

import java.io.IOException;

public class IndexService {
    private static final String INDEX_NAME = "gmt";


    public void createIndex() throws IOException {
        RestHighLevelClient restHighLevelClient = ESClient.getClient();
        CreateIndexRequest request = new CreateIndexRequest(INDEX_NAME);
        request.settings(Settings.builder().put("number_of_shards",5).put("number_of_replicas",1).build());
        XContentBuilder contentBuilder = JsonXContent.contentBuilder()
                .startObject()
                .startObject( "properties")
                .startObject("createDate").field("type","date").field("format","yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis").endObject()
                .startObject("sendDate").field("type","date").field("format","yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis").endObject()
                .startObject("longCode").field("type","long").endObject()
                .startObject("mobile").field("type","keyword").endObject()
                .startObject("corpName").field("type","keyword").endObject()
                .startObject("smsContent").field("type","text").field("analyzer","ik_max_word").endObject()
                .startObject("state").field("type","keyword").endObject()
                .startObject("opertaorId").field("type","integer").endObject()
                .startObject("province").field("type","keyword").endObject()
                .startObject("ipAddr").field("type","ip").endObject()
                .startObject("replyTotal").field("type","long").endObject()
                .startObject("fee").field("type","integer").endObject()
                .endObject()
                .endObject();
        request.mapping(contentBuilder);
        CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        System.err.println(response);
    }


    public void deleteIndex() throws IOException {
        RestHighLevelClient restHighLevelClient = ESClient.getClient();
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(INDEX_NAME);
        AcknowledgedResponse response = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        System.err.println(response);
    }
}
